package com.itheima.controller;

import com.itheima.domain.Student;
import com.itheima.service.StudentService;
import com.itheima.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

@WebServlet("/StudentServlet/*")
public class StudentServlet extends BaseServlet {
    //添加学生功能
    private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取前端页面的信息
        //姓名
        String name = req.getParameter("name");
        //年龄
        String age = req.getParameter("age");
        //成绩
        String score = req.getParameter("score");
        //学生信息交由service处理,获取返回数据(student对象)
        StudentService studentService = new StudentServiceImpl();
        studentService.add(name, Integer.parseInt(age), Integer.parseInt(score));
        //添加成功后在2s后自动跳转到首页
        resp.getWriter().write("添加成功,系统将于2秒后跳转到首页");
        resp.setHeader("Refresh", "2;URL=/studentInfo/pages/index.jsp");

    }

    //查询学生功能
    private void search(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //拿到学生信息集合
        StudentService studentService = new StudentServiceImpl();
        ArrayList<Student> students = studentService.search();
        //将学生信息集合保存到session
        req.getSession().setAttribute("students", students);
        //跳转到查询学生页面
        resp.setHeader("Refresh", "2;URL=/studentInfo/pages/search.jsp");
    }
}
